import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import {
  inject,
  observer,
} from 'mobx-react'

import {
  TextField,
  Button,
  withStyles,
  CircularProgress,
} from '@material-ui/core'

import UserWrapper from './user'
import loginStyle from './styles/login-style'

@inject(stores => (
  {
    appState: stores.appState,
    user: stores.appState.user,
  }
)) @observer
class UserLogin extends Component {
  constructor(props) {
    super(props)
    this.state = {
      accesstoken: '',
      helperText: '',
    }
    this.handleInput = this.handleInput.bind(this)
    this.handleLogin = this.handleLogin.bind(this)
  }

  componentWillMount() {
    if (this.props.user.isLogin) {
      this.props.history.replace('/user/info')
    }
  }

  handleInput(event) {
    this.setState({
      accesstoken: event.target.value.trim(),
    })
  }

  handleLogin() {
    const { accesstoken } = this.state
    if (!accesstoken) {
      this.setState({
        helperText: '必须填写AccessToken',
      })
      return
    }
    this.setState({
      helperText: '',
    })
    this.props.appState.login(accesstoken)
      .then(() => {
        this.props.history.replace('/user/info')
      })
      .catch((error) => {
        console.log(error)
      })
  }

  render() {
    const { classes, user } = this.props
    const { helperText, accesstoken } = this.state

    return (
      <UserWrapper>
        <div className={classes.root}>
          <Helmet>
            <title>User login</title>
          </Helmet>
          <TextField
            label="请输入Cnode AccessToken"
            placeholder="请输入Cnode AccessToken"
            require="true"
            helperText={helperText}
            value={accesstoken}
            onChange={this.handleInput}
            className={classes.input}
          />
          <Button
            variant="contained"
            color="primary"
            onClick={this.handleLogin}
            className={classes.loginButton}
          >
            登录
          </Button>
          {
            user.syncing ? (
              <div className={classes.loginLoading}>
                <CircularProgress color="primary" size={100} />
              </div>
            ) : null
          }
        </div>
      </UserWrapper>
    )
  }
}

UserLogin.wrappedComponent.propTypes = {
  appState: PropTypes.object.isRequired,
  user: PropTypes.object.isRequired,
}

UserLogin.propTypes = {
  classes: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
}

export default withStyles(loginStyle)(UserLogin)
